<script setup name="Copyright">
import {
  listCopyright,
  getCopyright,
  delCopyright,
  addCopyright,
  updateCopyright,
  checkCopyright
} from "@/api/manage/copyright";
import FileUpload from "@/components/FileUpload/index.vue";
import {listUser} from "@/api/system/user.js";
import {LoadAllParams} from "@/api/LoadAllParam.js";
import {getToken} from "@/utils/auth.js";
import {CircleCheck} from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore();
const {proxy} = getCurrentInstance();
const {
  check_status,
  software_right_scope,
  software_acquisition_method
} = proxy.useDict('check_status', 'software_right_scope', 'software_acquisition_method');
const fileList = ref([])
const copyrightList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCompletionDate = ref([]);
const daterangeAcquisitionDate = ref([]);
const showDetail = ref(false); // 控制详细显隐
const showCheck = ref(false); // 控制审批显隐
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    softwareName: null,
    acquisitionDate: null,
    acquisitionMethod: null,
    checkStatus: null,
    registrationNo: null,
    rightScope: null,
  },
  rules: {
    userId: [
      {required: true, message: "用户id不能为空", trigger: "change"}
    ],
    softwareName: [
      {required: true, message: "软件名称不能为空", trigger: "blur"}
    ],
    registrationNo: [
      {required: true, message: "登记号不能为空", trigger: "blur"}
    ],
    rightScope: [
      {required: true, message: "权利范围不能为空", trigger: "blur"}],
    acquisitionMethod: [
        {required: true, message: "获取方式不能为空", trigger: "blur"}],
    }
  });
const {queryParams, form, rules} = toRefs(data);

const proxyTarget = ref(import.meta.env.VITE_APP_BASE_URL);
const options = ref([])

// 接收文件组件传递的文件列表字符串
function handleUploadUpdate(newList) {
  form.value.scannedDocumentsUrl = newList
}

function getSoftwareCopyrightById(row) {
  showDetail.value = true;
  reset();
  getCopyright(row.id).then(response => {
    form.value = response.data;
    fileList.value = form.value.scannedDocumentsUrl
        ? form.value.scannedDocumentsUrl?.split(",")?.map(item => proxyTarget.value + item.trim())
        : [];
  });
}

/**
 * 审批
 */
function handleCheck(row) {
  reset();
  const _id = row.id || ids.value
  getCopyright(_id).then(response => {
    form.value = response.data;
    if (form.value.authors) {
      dynamicTags.value = form.value.authors.split(",")
    }
    showCheck.value = true;
    title.value = "审批";
  });
}

function check(status) {
  form.value.checkStatus = status;
  checkCopyright(form.value).then(res => {
    proxy.$modal.msgSuccess("操作成功");
    showCheck.value = false;
    getList();
  })
}

/** 查询软著管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCompletionDate && '' != daterangeCompletionDate) {
    queryParams.value.params["beginCompletionDate"] = daterangeCompletionDate.value[0];
    queryParams.value.params["endCompletionDate"] = daterangeCompletionDate.value[1];
  }
  if (null != daterangeAcquisitionDate && '' != daterangeAcquisitionDate) {
    queryParams.value.params["beginAcquisitionDate"] = daterangeAcquisitionDate.value[0];
    queryParams.value.params["endAcquisitionDate"] = daterangeAcquisitionDate.value[1];
  }

  listCopyright(queryParams.value).then(response => {
    copyrightList.value = response.rows;
    total.value = parseInt(response.total);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    softwareName: null,
    authors: null,
    advisor: null,
    completionDate: null,
    firstPublishDate: null,
    acquisitionDate: null,
    acquisitionMethod: null,
    rightScope: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    delFlag: null,
    remark: null,
    checkStatus: null,
    registrationNo: null,
    scannedDocumentsUrl: null
  };
  fileList.value = [];
  dynamicTags.value = [];
  proxy.resetForm("copyrightRef");
}

function openPDF(url) {
  window.open(url)
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCompletionDate.value = [];
  daterangeAcquisitionDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加软著管理";
  dynamicTags.value.push(userStore.name)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCopyright(_id).then(response => {
    form.value = response.data;
    if (form.value.authors) {
      dynamicTags.value = form.value.authors.split(",")
    }
    open.value = true;
    fileList.value = form.value.scannedDocumentsUrl ? form.value.scannedDocumentsUrl.split(',') : []
    title.value = "修改软著管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["copyrightRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.authors = authorList.value
        updateCopyright(form.value).then(res => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCopyright(form.value).then(res => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除软著管理编号为"' + _ids + '"的数据项？').then(function () {
    return delCopyright(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {

  });
}

const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/manage/copyright/importData"
})

function handleImport() {
  upload.title = "文件导入";
  upload.open = true;
}

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/copyright/export', {
    ...queryParams.value
  }, `copyright_${new Date().getTime()}.xlsx`)
}

/**
 * 查询用户
 * @param query
 */
const queryUser = (query) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      const params = {...LoadAllParams, userName: query}
      listUser(params).then(res => {
        options.value = res.rows
        console.log(res.rows)
      })
    }, 20)
  } else {
    options.value = []
  }
}

const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref()

const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}
const authorList = computed(() => {
  return dynamicTags.value.join(',')
})
const handleInputConfirm = () => {
  if (inputValue.value && inputValue.value !== '' && inputValue.value !== null) {
    dynamicTags.value.push(inputValue.value)
    if (authorList.value.lastIndexOf(',') >= 0) { //切分作者列表并且排除逗号
      form.value.authors = authorList.value.substring(0, authorList.value.lastIndexOf(','))
    } else {// 一个人无需排除逗号
      form.value.authors = authorList.value
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}
getList();
</script>

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="软件名称" prop="softwareName">
        <el-input
            v-model="queryParams.softwareName"
            placeholder="请输入软件名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="获得时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeAcquisitionDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item style="width:200px" label="取得方式" prop="acquisitionMethod">
        <el-select v-model="queryParams.acquisitionMethod" placeholder="取得方式" clearable>
          <el-option
              v-for="dict in software_acquisition_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item style="width:240px" label="审核状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable>
          <el-option
              v-for="dict in check_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登记号" prop="registrationNo">
        <el-input
            v-model="queryParams.registrationNo"
            placeholder="请输入登记号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交人" prop="userId">
        <el-select
            v-model="queryParams.userId"
            filterable
            remote
            reserve-keyword
            placeholder="提交人姓名"
            remote-show-suffix
            :remote-method="queryUser"
            :loading="loading"
            style="width: 240px"
        >
          <el-option
              v-for="item in options"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['manage:copyright:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['manage:copyright:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['manage:copyright:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload"
                   @click="handleImport" v-hasPermi="['manage:copyright:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['manage:copyright:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="copyrightList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column align="center" type="index" label="序号" width="66"/>
      <el-table-column label="登记号" align="center" width="200" prop="registrationNo"/>
      <el-table-column label="软件名称" align="center" width="120" show-overflow-tooltip prop="softwareName"/>
      <el-table-column label="作者列表" show-overflow-tooltip="show-overflow-tooltip" align="center" prop="authors"/>
      <el-table-column label="指导教师" align="center" prop="advisor"/>
      <el-table-column label="审核状态" align="center" prop="checkStatus">
        <template #default="scope">
          <el-icon v-show="scope.row.checkStatus === 0" color="orange">
            <Warning/>
          </el-icon>
          <el-icon v-show="scope.row.checkStatus === 1" color="green">
            <CircleCheck/>
          </el-icon>
          <el-icon v-show="scope.row.checkStatus === 2" color="red">
            <WarningFilled/>
          </el-icon>
        </template>
      </el-table-column>

      <el-table-column label="取得方式" width="120" align="center" prop="acquisitionMethod">
        <template #default="scope">
          <dict-tag :options="software_acquisition_method" :value="scope.row.acquisitionMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="权利范围" width="120" align="center" prop="rightScope">
        <template #default="scope">
          <dict-tag :options="software_right_scope" :value="scope.row.rightScope"/>
        </template>
      </el-table-column>
      <el-table-column label="开发完成日期" align="center" prop="completionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.completionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="首次发布日期" align="center" prop="firstPublishDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.firstPublishDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获得时间" align="center" prop="acquisitionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.acquisitionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button @click="getSoftwareCopyrightById(scope.row)" link type="primary" icon="View"
                     v-hasPermi="['manage:copyright:query']">详细
          </el-button>
          <el-button v-if="scope.row.checkStatus === 0" link type="primary" @click="handleCheck(scope.row)"
                     v-hasPermi="['manage:copyright:check']">审核
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['manage:copyright:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <el-dialog :title="title" v-model="showCheck" width="500px" append-to-body>
      <el-form>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :maxlength="200"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">

          <el-popconfirm @confirm="check(1)" title="确认通过？">
            <template #reference>
              <el-button type="primary">通过</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm @confirm="check(2)" title="确认驳回？">
            <template #reference>
              <el-button type="danger">驳回</el-button>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改软著管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="copyrightRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登记号" prop="registrationNo">
          <el-input v-model="form.registrationNo" placeholder="请输入登记号"/>
        </el-form-item>
        <el-form-item label="软件名称" prop="softwareName">
          <el-input v-model="form.softwareName" placeholder="请输入软件名称"/>
        </el-form-item>
        <el-form-item label="作者列表" prop="authors">
          <el-tag
              style="margin-right: 5px;margin-top: 5px"
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              size="large"
              @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="w-20"
              style="width: 120px"
              size="default"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
          />
          <el-button
              style="margin-right: 5px;margin-top: 5px"
              size="default" v-else class="button-new-tag" @click="showInput">
            +
          </el-button>
        </el-form-item>
        <el-form-item label="指导教师" prop="advisor">
          <el-input v-model="form.advisor" placeholder="请输入指导教师"/>
        </el-form-item>
        <el-form-item label="完成日期" prop="completionDate">
          <el-date-picker clearable
                          v-model="form.completionDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开发完成日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发布日期" prop="firstPublishDate">
          <el-date-picker clearable
                          v-model="form.firstPublishDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择首次发布日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="获得时间" prop="acquisitionDate">
          <el-date-picker clearable
                          v-model="form.acquisitionDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择获得时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="取得方式" prop="acquisitionMethod">
          <el-select v-model="form.acquisitionMethod" placeholder="请选择取得方式">
            <el-option
                v-for="dict in software_acquisition_method"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权利范围" prop="rightScope">
          <el-select v-model="form.rightScope" placeholder="请选择权利范围">
            <el-option
                v-for="dict in software_right_scope"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :maxlength="200"/>
        </el-form-item>
        <el-form-item label="扫描件" prop="remark">
          <file-upload :file-type="['png','jpg','jpeg','pdf']" v-model="fileList"
                       @update:modelValue="handleUploadUpdate"></file-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog @close="fileList = []" v-model="showDetail" title="详细信息" width="1000px" append-to-body>
      <el-descriptions column="2" border>
        <el-descriptions-item align="center" label="软著名称">
    <span>
      {{ form.softwareName }}
    </span>
        </el-descriptions-item>
        <el-descriptions-item align="center" label="作者列表">
    <span>
      {{ form.authors }}
    </span>
        </el-descriptions-item>

        <el-descriptions-item align="center" label="扫描件" class="image-item">
          <div class="image-container" v-if="fileList && fileList.length > 0">
            <el-image
                v-for="(item, index) in (fileList || [])?.filter(it => !it?.toLowerCase().endsWith('.pdf'))"
                :key="index"
                :src="item"
                class="preview-image"
                :preview-src-list="(fileList || [])?.filter(it => !it?.toLowerCase().endsWith('.pdf'))"
            />
            <el-image
                v-for="(item, index) in (fileList || [])?.filter(it => it?.toLowerCase().endsWith('.pdf'))"
                :key="'pdf-'+index"
                :src="'/pdf-icon.png'"
                class="preview-image"
                @click="openPDF(item)"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<style scoped>

/* 图片容器样式，与label同高 */
.image-item .image-container {
  min-height: 40px; /* 与label高度一致 */
  display: flex;
  align-items: center;
}

/* 图片样式 */
.preview-image {
  width: 100px;
  height: 100px;
  margin-top: 10px;
  margin-right: 10px;
  cursor: pointer;
}

</style>
